<!doctype html>
<html lang="zh-CN">

	<head>
		<link rel="Stylesheet" type="text/css" href="css/buttons.css" />
		<script src="js/common.js" type="text/javascript"></script>
		<!-- <script src="js/js_sdk/plus-websocket/index.js" type="text/javascript"></script> -->
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<base href="http://webapi.amap.com/ui/1.1/ui/misc/PositionPicker/examples/" />
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
		<title>拖拽选址</title>

		<style>
			html,
    body {
        height: 100%;
        margin: 0;
        width: 100%;
        padding: 0;
        overflow: hidden;
        font-size: 13px;
    }
    
    .map {
        height: 100%;
        width: 100%;
        float: left;
    }
    
    #right {
        color: #444;
        background-color: #f8f8f8;
        width: 0%;
        float: left;
        height: 100%;
    }
    
    #start,
    #stop,
    #right input {
        margin: 4px;
        margin-left: 15px;
    }
    
    .title {
        width: 100%;
        background-color: #dadada
    }
/*    buttonTT {
	 background-color: #39B54A; 
				color:white;
	} */
   #buttonGO {
	      border-radius: 100px;
        border: solid 0px;
       /* background-color: #84B91F; */
		color:white;
		width: 100px;
		height: 100px;
		position: absolute;
		z-index: 10000;
		top: 80%;
		right: 35%;
		font-size: 23px;
    }
    #DriverGO {
    	      border-radius: 100px;
         border: solid 0px;
        background-color: #4CB0F9;
    		color:white;
    		width: 100px;
    		height: 100px;
    		position: absolute;
    		z-index: 10000;
    		top: 80%;
    		right: 10%;
    		font-size: 23px;
     }
	 #TalkGO{
		 border-radius: 100px;
		  border: solid 0px;
		 background-color: #5246E2;
		 	color:white;
		 	width: 100px;
		 	height: 100px;
		 	position: absolute;
		 	z-index: 10000;
		 	top: 80%;
		 	right: 65%;
		 	font-size: 23px;
	 }
    .c {
        font-weight: 600px;
        padding-left: 15px;
        padding-top: 4px;
    }
    
    #lnglat,
    #address,
    #nearestJunction,
    #nearestRoad,
    #nearestPOI,
    .title {
        padding-left: 15px;
    }
	
	
	
	    #pickerBox {
	        position: absolute;
	        z-index: 9999;
	        top: 50px;
	        right: 30px;
	        width: 300px;
	    }
	    
	    #pickerInput {
	        width: 200px;
	        padding: 5px 5px;
	    }
	    
	    #poiInfo {
	        background: #fff;
	    }
	    
	    .amap_lib_placeSearch .poibox.highlight {
	        background-color: #CAE1FF;
	    }
	    
	    .amap_lib_placeSearch .poi-more {
	        display: none!important;
	    }
    </style>
	</head>

	<body>
		<button id="TalkGO" class="button button-glow button-circle button-action button-jumbo"><i class="fa fa-thumbs-up" id="Talk">聊天室</i></button>
		<button id="buttonGO" class="button button-glow button-circle button-action button-jumbo"><i class="fa fa-thumbs-up" id="GOID">GO</i></button>
		<!-- <button id="DriverGO" class="button button-glow button-circle button-action button-jumbo"><i class="fa fa-thumbs-up" id="DriverID">订单列表</i></button> -->
		<div id="container" class="map" tabindex="0"></div>
		<div id="pickerBox">
			<input id="pickerInput" placeholder="输入关键字选取地点" />
			<div id="poiInfo"></div>
		</div>
		<div id="container" class="map" tabindex="0"></div>
		<div id="right">
			<!--       <div>
            <div class='title'>选择模式</div>
            <input type='radio' name='mode' value='dragMap' checked>拖拽地图模式</input>
            </br>
            <input type='radio' name='mode' value='dragMarker'>拖拽Marker模式</input>
        </div> -->
			<div>
				<div class='c'>经纬度:</div>
				<input id='lnglat' type='text'>

				<div class='c'>地址:</div>
				<input id='address' type='text'>
				<input id='distance' type='text'>
				<input id='isok' type='text'>
				<input id='money' type='text'>
			</div>
		</div>

		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
		<script type="text/javascript" src="http://webapi.amap.com/maps?v=2.0&key=0c84208de6aaff3252ba3f7cd1d2a6c8&plugin=AMap.ToolBar"></script>
		<!-- UI组件库 1.0 -->
		<script src="http://webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>

		<script type="text/javascript">
			var Endvalue = JSON.parse(getQuery('data'));
			//取url中的参数值
			function getQuery(name) {
				// 正则：[找寻'&' + 'url参数名字' = '值' + '&']（'&'可以不存在）
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					// 对参数值进行解码
					return decodeURIComponent(r[2]);
				}
				return null;
			};
			var isDO = false;
			var money = null;
			document.addEventListener('UniAppJSBridgeReady', function() {
				
				//点击了架势列表按钮触发	
			// 	document.getElementById('DriverGO').addEventListener('click', function() {
			// 		var url='/pages/movehouse/dirver/dirver';
			// 		uni.navigateTo({
			// 			url:url
			// 		});
			// 	});
				
				//点击了聊天室按钮触发
				document.getElementById('TalkGO').addEventListener('click', function() {
					if(orderSn!=null&&orderSn!=''&&Endvalue.userId!=null){
						var url='/pages/movehouse/moretalk/morepeople?orderSn='+orderSn+"&userId="+Endvalue.userId;
						uni.navigateTo({
							url:url
						});	
					}
				});	
				
				
				
			});
			var startaddress=null;
			var startposition=null;
			document.getElementById('buttonGO').addEventListener('click', function() {
				if(isDO==false){
				startposition = document.getElementById('lnglat').value;
				startaddress = document.getElementById('address').value;
				localStorage.setItem('GO_lng', startposition);
				localStorage.setItem('GO_address', startaddress);
				
				Howmoney(startposition);
				}else {
					underOrder();
				}
				//如果条件达到执行弹窗进行最后确认
			});
			var socketUrl='ws://'+baseIpUrl+'websocket/'+Endvalue.userId;
			var SocketTask = null;
			var orderSn=null;
			//下单
			function doOrder() {
				//开启监听判断
				SocketTask=new WebSocket(socketUrl);
				SocketTask.onopen = function() {
				        console.log("websocket已打开");
				        //socket.send("这是来自客户端的消息" + location.href + new Date());
				    };
			
				
				var startaddress=localStorage.getItem('GO_address');
				var startpostion=localStorage.getItem('GO_lng'); 
				var order={
					uid: Endvalue.userId,
					tid: Endvalue.trucksId,
					cid: Endvalue.comId,
					price: Endvalue.price,
					totalAmount:totalAmount,
					distance: distance,
				};
				var address ={
							startAddress: startaddress,
							endAddress: Endvalue.address.myaddress,
							uidxy: startpostion,
							overxy: Endvalue.address.postion,
						};
				var addressAndorder={order,address};
				$.ajax({
					url: baseUrl + 'order/doOrder',
					method: 'POST',
					dataType: 'json',
					contentType:"application/json",
					async: false,
					data: JSON.stringify(addressAndorder),
					success: function(res){
						if (res.flag) {
							isDO=true;
							timeSave();
							orderSn=res.data;
							SocketTask.onmessage = function(msg) {
										var message=JSON.parse(msg.data);
							            //发现消息进入    开始处理前端触发逻辑
										if(message.code==20000){
										endtime();
										SocketTask.close();
								}	
							}
						}else{
							isDO=false;
							AMapUI.loadUI(['overlay/SimpleInfoWindow'], function(SimpleInfoWindow) {
								//弹出层
								var infoWindow2 = new SimpleInfoWindow({
									infoTitle: '<strong>订单申请失败</strong>',
									infoBody: '<p>' +res.message+ '</p>',
									offset: new AMap.Pixel(0, -31)
								});
						});
						SocketTask.close();
						}
					}
				})
			};
			
			var timer=null;
			var nums=null;
			var isDO=false;
			//计时器
			function timeSave() {
					    nums=null;
						var hour, minute, second; /*时 分 秒*/
						hour = minute = second = 0; //初始化
						var millisecond = 0; //毫秒
						timer = setInterval(() => {
							millisecond = millisecond + 50;
							// console.log("---millisecond----"+millisecond);
							if (millisecond >= 1000) {
								millisecond = 0;
								second = second + 1;
							}
							if (second >= 60) {
								second = 0;
								minute = minute + 1;
							}
			 
							if (minute >= 60) {
								minute = 0;
								hour = hour + 1;
							}
							// console.log("-------"+hour+'时'+minute+'分'+second+'秒');
							nums =minute+'分'+second+'秒';
							$("#GOID").text(nums);
							
						}, 50);
			};
				
				//取消订单的方法
				function underOrder(){
					SocketTask.close();
					var ss=this;
					AMapUI.loadUI(['overlay/SimpleInfoWindow'], function(SimpleInfoWindow) {
						//弹出层
						var infoWindow2 = new SimpleInfoWindow({
							infoTitle: '<strong>取消订单</strong>',
							infoBody: '<p>确定要取消订单吗' + '</p>'+'<button class="mybtn buttonTT">确定</button>',
							offset: new AMap.Pixel(0, -31)
						});
						infoWindow2.get$InfoBody().on('click', '.mybtn', function(event) {
						
							//阻止冒泡
							event.stopPropagation();
							endtime();	
							SocketTask.close();
							infoWindow2.close();
							
						});
						infoWindow2.open(map, map.getCenter());
						
					});
			};
			
				function endtime() {
					isDO=false;
					 clearInterval(timer);
					 	$("#GOID").text('GO');
				};
				//司机的方法
				function DriverGo(){
					console.log('司机订单列表前往')
					uni.navigateTo({
						url:'/pages/movehouse/dirver/dirver',
					});
				};
			var distance=null;
			//计算金额的请求
			function Howmoney(startposition) {

				var a = 0;
				var HashMap = null;
				$("#isok").val(1);
				var ajaxhowmoney = $.ajax({
					url: 'https://restapi.amap.com/v3/direction/walking?origin=' + startposition + '&destination=' + Endvalue.address
						.postion + '&key=1f5cfb770d01a1a0d8289169188de6b3',
					method: 'GET',
					dataType: 'json',
					async: false,
					success: function(res) {
						if (res.status) {
							isok = true;
							distance= res.route.paths[0].distance;
							HashMap = {
								uid: Endvalue.userId,
								price: Endvalue.price,
								tid: Endvalue.trucksId,
								distance: distance,
							};
							$("#isok").val(2);
						}
					}
				});
				if ($("#isok").val() == 2) {

					HowMoneyEnd(HashMap);
				}

			};
			
			//计算金额的结束后调用弹窗等等
			var totalAmount=0;
			function HowMoneyEnd(HashMap) {
				$.ajax({
					url: baseUrl + 'order/Howmoney',
					method: 'POST',
					dataType: 'json',
					contentType: 'application/json;charset=utf-8',
					async: false,
					data: JSON.stringify(HashMap),
					success: function(res) {
						if (res.flag) {
							money = res.data;
							totalAmount=money;
							AMapUI.loadUI(['overlay/SimpleInfoWindow'], function(SimpleInfoWindow) {
								//弹出层
								var infoWindow2 = new SimpleInfoWindow({
									infoTitle: '<strong>订单确认</strong>',
									infoBody: '<p>您的订单预计支付金额为' + money +
										'</p><button class="mybtn buttonTT">确定</button><button class="mybtnNo amap-ui-infowindow-close" style="margin-left:50px;">取消</button>',
									//基点指向marker的头部位置
									offset: new AMap.Pixel(0, -31)
								});


								infoWindow2.get$InfoBody().on('click', '.mybtn', function(event) {

									//阻止冒泡
									event.stopPropagation();
									doOrder();	
									infoWindow2.close();

								});
								infoWindow2.get$InfoBody().on('click', '.mybtnNo', function(event) {

									//阻止冒泡
									event.stopPropagation();
									infoWindow2.close();
						

								});
								infoWindow2.open(map, map.getCenter());
							});

						} else {
							isDO = false;
							AMapUI.loadUI(['overlay/SimpleInfoWindow'], function(SimpleInfoWindow) {
								//弹出层
								var infoWindow2 = new SimpleInfoWindow({
									infoTitle: '<strong>下单错误</strong>',
									infoBody: '<p>距离终点太近' + '</p>',
									offset: new AMap.Pixel(0, -31)
								});
								infoWindow2.open(map, map.getCenter());
							});
						}
					}
				});
			};
			
			//构造一个选址器 这个可以用来拖拽选址
			var map = null;
			AMapUI.loadUI(['misc/PositionPicker', 'misc/PoiPicker'],
				function(PositionPicker, PoiPicker) {
					map = new AMap.Map('container', {
						zoom: 20,
						scrollWheel: false
					});
					var positionPicker = new PositionPicker({
						mode: 'dragMap',
						map: map
					});
					var infoWindow = new AMap.InfoWindow({
						offset: new AMap.Pixel(0, -40)
					});
					positionPicker.on('success', function(positionResult) {
						document.getElementById('lnglat').value = positionResult.position;
						document.getElementById('address').value = positionResult.address;
						infoWindow.setContent('POI信息: <pre>' + '地址:' + positionResult.address + '</pre>');
						infoWindow.open(map, positionResult.position);
					});
					positionPicker.on('fail', function(positionResult) {
						document.getElementById('lnglat').value = ' ';
						document.getElementById('address').value = ' ';

					});
					var onModeChange = function(e) {
						positionPicker.setMode(e.target.value)
					}
					positionPicker.start();
					map.panBy(0, 1);

					map.addControl(new AMap.ToolBar({
						liteStyle: true
					}))


					//poiPicker 
					var poiPicker = new PoiPicker({
						//city:'北京',
						input: 'pickerInput'
					});

					//初始化poiPicker
					poiPickerReady(poiPicker);

					function poiPickerReady(poiPicker) {

						window.poiPicker = poiPicker;

						var marker = new AMap.Marker();


						//选取了某个POI
						poiPicker.on('poiPicked', function(poiResult) {

							var source = poiResult.source;
							poi = poiResult.item;
							positionPicker.start(poi.location);
							infoWindow.setContent('POI信息: <pre>' + '名称:' + poi.name + '\n地址:' + poi.address + '</pre>');
							infoWindow.open(map, poi.location);
						});
					}

					//       socket.onSocketOpen(function(e) {  
					//                   console.log('websocket open');
					//               });  
								// socket.onSocketError(function (res) {
								//   console.log('WebSocket连接打开失败，请检查！');
								// });		

							
						

				});



				
				
				
		</script>
	</body>

</html>
